/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package uy.edu.ort.ws.cliente;

import java.io.IOException;
import java.net.URL;
import java.util.Iterator;
import java.util.Properties;
import javax.swing.JOptionPane;
import uy.edu.ort.dominio.Fuente;
import uy.edu.ort.dominio.ListaTopicos;
import uy.edu.ort.dominio.ManejoJSON;
import uy.edu.ort.dominio.Noticia;

/**
 *
 * @author Administrador
 */
public class VentanaFuente extends javax.swing.JFrame {

    
    private static URL url=null;
    
    private static int idNoticia = 1;
    /**
     * Creates new form VentanaFuente
     */
    public VentanaFuente() {
        initComponents();  
        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        txtIdFuente = new javax.swing.JTextField();
        txtCodigo = new javax.swing.JTextField();
        cboTopico = new javax.swing.JComboBox();
        btnConsultar = new javax.swing.JButton();
        txtTitulo = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtContenido = new javax.swing.JTextArea();
        btnEnviar = new javax.swing.JButton();
        lblMensaje = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Aplicación Cliente Fuente");

        jLabel1.setText("Id Fuente");

        jLabel2.setText("Codigo");

        jLabel3.setText("Topico");

        jLabel4.setText("Titulo");

        jLabel5.setText("Contenido");

        btnConsultar.setText("Consultar Topicos");
        btnConsultar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConsultarActionPerformed(evt);
            }
        });

        txtTitulo.setEditable(false);

        txtContenido.setEditable(false);
        txtContenido.setColumns(20);
        txtContenido.setRows(5);
        jScrollPane1.setViewportView(txtContenido);

        btnEnviar.setText("Enviar Noticia");
        btnEnviar.setEnabled(false);
        btnEnviar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEnviarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txtIdFuente)
                            .addComponent(txtCodigo)
                            .addComponent(cboTopico, 0, 116, Short.MAX_VALUE)
                            .addComponent(txtTitulo))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnConsultar, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(btnEnviar, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblMensaje, javax.swing.GroupLayout.PREFERRED_SIZE, 298, javax.swing.GroupLayout.PREFERRED_SIZE)))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtIdFuente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(cboTopico, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnConsultar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtTitulo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel5)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnEnviar, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblMensaje, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(31, Short.MAX_VALUE))
        );

        jLabel1.getAccessibleContext().setAccessibleName("lblFuenteID");
        jLabel2.getAccessibleContext().setAccessibleName("lblCodAutoriza");
        jLabel3.getAccessibleContext().setAccessibleName("lblTopico");
        jLabel4.getAccessibleContext().setAccessibleName("lblTitulo");
        jLabel5.getAccessibleContext().setAccessibleName("lblContenido");
        txtIdFuente.getAccessibleContext().setAccessibleName("txtIdFuente");
        txtCodigo.getAccessibleContext().setAccessibleName("txtCodigo");
        cboTopico.getAccessibleContext().setAccessibleName("cboTopico");
        btnConsultar.getAccessibleContext().setAccessibleName("btnConsultar");
        txtTitulo.getAccessibleContext().setAccessibleName("txtTitulo");
        jScrollPane1.getAccessibleContext().setAccessibleName("txtContenido");
        btnEnviar.getAccessibleContext().setAccessibleName("btnEnviar");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnConsultarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConsultarActionPerformed
        // TODO add your handling code here:
//        if (this.ChequearCamposConsultaTopicos())
//        {
            if (url!=null){
                ServiciosAgenciaWS service = (ServiciosAgenciaWS) new ServiciosAgenciaWS_Service(url).getServiciosAgenciaWSPort();
                //Creo objeto Fuente, lo paso a JSON y la mando por web services
                Fuente fuente = new Fuente(txtIdFuente.getText(),txtCodigo.getText());
                
                ManejoJSON mj = new ManejoJSON();                
                String identificacion = mj.ObjetoToJSON(fuente);
                //System.out.println("LLEGAAAAAA CLIENTEEE");
                //obtener topicos de WS
                String topicos = service.consultarTopicos(identificacion);
                System.out.println("Topicos: " + topicos);
                lblMensaje.setText("Topicos: " + topicos);
                cboTopico.removeAllItems();
                if (!topicos.equals("Fuente inválida"))
                {
                    
                        ListaTopicos lista = new ListaTopicos();
                        lista = mj.JSONToListaTopicos(topicos);
               
                        Iterator<String> iterador = lista.getLista().iterator();  
  
                        while (iterador.hasNext()) {  
                            cboTopico.addItem(iterador.next().toString()); 
                        }
                    
                        txtTitulo.setEditable(true);
                        txtContenido.setEditable(true);
                        btnEnviar.setEnabled(true);
                    
                    
                }
                else{
                    
                   lblMensaje.setText("Fuente no autorizada, intente nuevamente.");
                   txtIdFuente.setText("");
                   txtCodigo.setText("");
                   txtIdFuente.selectAll(); 
                }
                 

            } else {
                System.out.println("No se pudo obtener correctamente la URL");
                lblMensaje.setText("No se pudo obtener correctamente la URL");
            }
//        } else {
//            JOptionPane.showMessageDialog(null, "Debe completar los campos IdFuente y Código.",
//            "Atención", JOptionPane.INFORMATION_MESSAGE);
//        }
        
    }//GEN-LAST:event_btnConsultarActionPerformed

    private void btnEnviarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEnviarActionPerformed
        // TODO add your handling code here:
        if (url!=null){
            ServiciosAgenciaWS service = (ServiciosAgenciaWS) new ServiciosAgenciaWS_Service(url).getServiciosAgenciaWSPort();
            
            //Creo objeto Noticia, lo paso a JSON y la mando por web services
                        
            Noticia noticia = new Noticia(idNoticia,txtIdFuente.getText(),txtCodigo.getText(),txtTitulo.getText(),txtContenido.getText(),cboTopico.getSelectedItem().toString());            
                
            ManejoJSON mj = new ManejoJSON();                
            String noti = mj.ObjetoToJSON(noticia);
            
            //probando metodo mandar noticia de WS
            String confirmacion = service.recibirNoticia(noti);
            lblMensaje.setText(confirmacion);
            idNoticia += 1;
            //System.out.println("Confirmacion: " + confirmacion);

        } else {
            System.out.println("No se pudo obtener correctamente la URL");
            lblMensaje.setText("No se pudo obtener correctamente la URL");
        }
    }//GEN-LAST:event_btnEnviarActionPerformed

    //Métodos para verificar que campos sean correctos
    private boolean ChequearCamposConsultaTopicos()
    {
        return !txtIdFuente.toString().isEmpty() && !txtCodigo.toString().isEmpty();
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VentanaFuente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VentanaFuente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VentanaFuente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VentanaFuente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new VentanaFuente().setVisible(true);
            }
        });
        
        

        //url = new URL("http://localhost:8080/ServiciosAgenciaWS/ServiciosAgenciaWS?wsdl");
        //Leo la URL desde el archivo de configuración
        try {
            LeerArchivo archivoPropiedades = new LeerArchivo();
            Properties prop = archivoPropiedades.getProperties();
            try {
                url = new URL(archivoPropiedades.getProperty(prop, "URL"));
            } catch (Exception e) {
                System.out.println("No se encuentra la clave URL en el archivo de propiedades");
                
            }
        } catch (Exception ee) {
            System.out.println("No se puede abrir el archivo properties");
        }

    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnConsultar;
    private javax.swing.JButton btnEnviar;
    private javax.swing.JComboBox cboTopico;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblMensaje;
    private javax.swing.JTextField txtCodigo;
    private javax.swing.JTextArea txtContenido;
    private javax.swing.JTextField txtIdFuente;
    private javax.swing.JTextField txtTitulo;
    // End of variables declaration//GEN-END:variables
}
